<?php
namespace app\admin\controller;
use x\my\File;
class Fahuo extends Base
{
    //列表
    public function lists(){
        if(is_post()){
            $d = $this->post;
            $map = [
                ['and','a.pay_status','=',1],
                ['and','a.fahuo_status','=',0],
                ['and','a.refund_status','=',0],
            ];
            if($d['keyword']) $map[] = ['and','b.username|b.phone','like',"%{$d['keyword']}%"];
            if($d['sh_keyword']) $map[] = ['and','a.sh_name|a.sh_phone|sh_address','like',"%{$d['sh_keyword']}%"];
            if($d['title'])   $map[] = ['and','a.title','like',"%{$d['title']}%"];
            if($d['min_time']!='') $map[] = ['and','a.create_time','>=',strtotime($d['min_time'])];
            if($d['max_time']!='') $map[] = ['and','a.create_time','<=',strtotime($d['max_time'])];
            $w  = where($map);
            $sql = "select a.*,group_concat(concat_ws('',title,'(',goods_price_title,')','X',nums) separator '<br/>') as goods_title,sum(total_money) as order_total_money,b.username from order_goods as a
                          left join user b on a.user_id=b.id $w[0]
                          group by a.order_no order by a.id desc".limit($d['page'],$d['limit']);
            $rs = $this->db->query($sql, $w[1],'',true);

            //下载,圆通模板
            if(isset($d['is_down']) && $d['is_down']){
                $sql = "select a.*,group_concat(concat_ws('',title,'(',goods_price_title,')','X',nums) separator '<br/>') as goods_title,b.username from order_goods as a
                              left join user b on a.user_id=b.id $w[0]
                              group by a.order_no order by a.id desc";
                $rs_down = $this->db->query($sql, $w[1]);
                foreach ($rs_down as $k => $v) {
                    $rs_down[$k]['fahuo_name'] = $this->sys['fahuo_name'];
                    $rs_down[$k]['fahuo_phone'] = $this->sys['fahuo_phone'];
                    $rs_down[$k]['fahuo_dizhi'] = $this->sys['fahuo_dizhi'];
                    $rs_down[$k]['fahuo_youbian'] = $this->sys['fahuo_youbian'];
                    $rs_down[$k]['daishouhuokuan'] = '';
                    $rs_down[$k]['shoujianrenyuobian'] = '';
                    $rs_down[$k]['shoujianrenguhua'] = '';
                    $rs_down[$k]['baojiajine'] = '';
                    $rs_down[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                }
                $title = ['订单编号','物流公司编码','物流单号','会员账号','用户id','商品名称','数量','单价','总价','使用积分','获得积分','收件人姓名','收件人地址','收件人手机号','发件人姓名','发件人电话','发件人地址','发件人邮编','代收货款','备注','收件人邮编','收件人固话','保价金额','日期'];
                $fields= ['id','kd_code','kd_no','username','user_id','goods_title','nums','goods_price_price','total_money','use_points','points','sh_name','sh_address','sh_phone','fahuo_name','fahuo_phone','fahuo_dizhi','fahuo_youbian','daishouhuokuan','kd_note','shoujianrenyuobian','shoujianrenguhua','baojiajine','create_time'];
                $file = com_csv($rs_down,$title,$fields,'ordergoods');
                cookie('js_url',$file);
            }
            if($rs){
              $rule = [
                  'pay_status' => function($v){return c("type.pay_status.{$v}");},
                  'fahuo_status' => function($v){return c("type.fahuo_status.{$v}");},
                  'create_time' => 'com_time_format',
              ];
              $data = com_format($rs[0],$rule);
              suc($data,$rs[1]);
            }else{
                suc([],0);
            }
        }
        $this->fetch();
    }

    //删除
    public function del(){
      if(is_post()){
        $order_no = $this->post["order_no"];
        $list = $this->db->query("select * from order_goods where order_no=?",[$order_no]);
        $rs = $this->db->delete("order_goods",$order_no,'order_no');
        $msg = "删除了订单,内容为:" . json_encode($list,JSON_UNESCAPED_UNICODE);
        //添加日志
        m('Log','xcom')->record($this->userinfo["id"], $msg,'admin_user');
        if($rs){
            cookie('js_msg','删除成功');
            cookie('js_function','close|reload');
            return suc();
        }else{
            return err("删除失败");
        }
      }
    }


    //发货
    public function doit(){
      if(is_post()){
        $d = $this->post();

        $map = [
          ['and','id','in',$d['ids']]
         ];
         $w = where($map);
         $order_no = $this->db->query("select order_no from order_goods {$w[0]}",$w[1],1);

        #更新订单记录
        $rs = $this->db->query("update order_goods set fahuo_status=1,kd_time=?,kd_no=?,kd_name=?,kd_note=? where id in(".$d["ids"].")",[time(),$d['kd_no'],$d['kd_name'],$d['kd_note']]);

        m('OrderGoods','c')->upfahuo($order_no['order_no']);

        if($rs){
            cookie('js_msg','发货成功');
            cookie('js_function','preload');
            return suc();
        }else{
            return err("发货失败");
        }

        //$ids = explode(",",$d["ids"]);
        //unset($d["ids"]);

        // foreach ($ids as $v) {
        //     $d['id'] = $v;
        //     $d['fahuo_status'] = 1;
        //     $mysql[] = $this->db->update("order_goods",$d);
        //     #更新订单记录
        //     $mysql[] = $this->db->query("update order_goods_no a,order_goods b set b.status=?,update_time=? where order_no=",[3,time(),$order_goods_no['id']]);
        // }

        suc();
      }
      $d = $this->get;
      $ids = implode(",",$d["ids"]);
      $this->fetch(["ids" => $ids]);
    }

    #批量删除
    function delall(){
      if(is_post()){
            $d = $this->post;
            $ids = $d['id'];
            foreach($ids as $id){
                $info = $this->db->find('order_goods',$id);
                if($info){
                    //添加日志
                    $list = $this->db->query("select * from order_goods where order_no=?",[$info['order_no']]);
                    $msg = "删除了订单,内容为:" . json_encode($list,JSON_UNESCAPED_UNICODE);
                    m('Log','xcom')->admin($this->userinfo["id"], $msg,'admin_user');
                    $this->db->delete('order_goods',$info['order_no'],'order_no');
                }
            }
            cookie('js_msg','删除成功');
            cookie('js_function','close|reload');
            return suc();
      }
    }

    //发货
    public function detail(){

        if(is_post()){
           $d = $this->post;
           $rule = [
               'kd_id'=>'require',
                'ids' => 'require'
           ];
           $msg = [
               'kd_id.require' => '请选择快递公司',
               'ids.require' => "请选择商品"
           ];
           check($rule,$msg,$d);
           $ids = $d["ids"];
           //快递公司
           $info = $this->db->query("select * from express where id = ?",[$d['kd_id']],1);
           // $d['kd_name'] = $info['name'];
           // $d['kd_code'] = $info['kuaidi_no'];
           // //
           // unset($d["ids"]);
           // unset($d["kd_id"]);
           // foreach ($ids as $v) {
           //     $d['id'] = $v;
           //     $d['fahuo_status'] = 1;
           //     $d['update_time'] = time();
           //     $rs = $this->db->update("order_goods",$d);
           // }
           $map = [
            ['and','id','in',$ids]
           ];
           $w = where($map);
           $order_no = $this->db->query("select order_no from order_goods {$w[0]}",$w[1],1);
           #更新订单记录
            $rs = $this->db->query("update order_goods set fahuo_status=1,kd_time=?,kd_no=?,kd_name=?,kd_code=?,kd_note=? where id in(".implode(',',$d["ids"]).")",[time(),$d['kd_no'],$info['name'],$info['kuaidi_no'],$d['kd_note']]);

            m('OrderGoods','c')->upfahuo($order_no['order_no']);

           if($rs){
               cookie('js_msg','发货成功');
               cookie('js_function','reload');
               return suc();
           }else{
               return err("发货失败");
           }
        }
        $order_no = $this->get("order_no");
        $sql = "select * from order_goods where order_no = ? and refund_status=0 order by id desc";
        $rs = $this->db->query($sql,[$order_no]);

        $user = $this->db->query("select * from user where id = ?",[$rs[0]['user_id']],1);
        //快递公司列表
        $elist = $this->db->query("select * from express where status = ? order by id asc",[0]);
        $no_info = $this->db->query("select * from order_goods_no where order_no =?",[$order_no],1);
        $this->fetch(["list" => $rs,'elist'=>$elist,'user'=>$user,"no_info"=>$no_info]);
    }

    //下载订单
    public function downOrder(){
        if(is_post()){//下载
            $d = $this->post;
            $rule = [
                'nos'=>'require',
                'eid'=>'require',
            ];
            $msg = [
                'eid.require' => '请选择快递公司',
            ];
            check($rule,$msg,$d);
            $file = m('OrderGoods','c')->downOrder($d['nos'],$d['eid']);
            cookie('js_url',$file);
            cookie('js_function','preload');
            suc();
        }
        $d = $this->get;
        $orderids = join(',',$d['ids']);
        if(empty($orderids)){
            $orderids =0;
        }
        //查询订单
        $rs = $this->db->query("select * from order_goods where id in ($orderids)",[]);
        $order_nos = join(',',array_column($rs,'order_no'));

        //快递公司列表
        $elist = $this->db->query("select * from express where status = ?",[0]);
        $this->fetch(['nos'=>$order_nos,'elist'=>$elist],'',false);
    }

    //上传文档
    public function upOrder(){
        if(is_post()){
            $rs = File::get_upload_file_info('file');
            if(!$rs || $rs['type']!='application/vnd.ms-excel'){
                err('只能上传csv文件');
            }
            $temp = [];
            $file = fopen($rs['temp'],'r');
            while ($data = fgetcsv($file)) { //每次读取CSV里面的一行内容
                $temp[] = $data;
            }
            fclose($file);
            $arr= eval('return ' . mb_convert_encoding(str_replace("' . \"\\0\" . '", '', var_export($temp, true)) .';',"utf-8","gbk"));
            $msg = "";
            $model = s("orderGoods",'c');
            foreach ($arr as $k => $v) {
                $rs = $model->edit($v);
                if(!$rs){
                    $msg .= $v[0] . ",";
                }
            }
            if($msg != ""){
                cookie('js_msg','发货成功');
                cookie('js_function','reload');
                return suc();
            }else{
                return err($msg."发货失败");
            }
        }
        $this->fetch();
    }
}
